<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>火箭飞天</title>
    <style>
        body {
            height: 2000px;
            background: linear-gradient(to bottom, skyblue 30%, pink 70%);
        }

        .box {
            /* border: 1px solid red; */
            height: 249px;
            width: 149px;
            background-image: url("./rocket.png");
            background-repeat: no-repeat;
            background-position: 0 0;
            position: fixed;
            bottom: 0;
            right: 50px;
            display: none;
        }

        .box:hover {
            background-position: -149px 0;
        }
        .active {
            animation: fly 0.3s steps(3) infinite;
        }

        @keyframes fly {
            from {
                background-position: -298px;
            }

            to {
                background-position: -745px 0;
            }
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <script>
        var div = document.querySelector(".box");
        var timer = null;
        var rocket_offsetTop;
        div.onclick = function () {
            if(timer) return;      // 避免双击或者多次点击时出现滚动条滚动不下来
            div.classList.add("active");
            var scrollTop = window.scrollY; 
            var b = window.scrollY;     // 滚动条位置
            rocket_offsetTop = this.offsetTop + 250;
            // console.log(scrollTop);
            rocket_v = rocket_offsetTop/50;
            timer = setInterval(function () {
                scrollTop -= (b / 50); //滚动条位置减小
                div.style.top = div.offsetTop - rocket_v + "px";    // 火箭位置变化
                window.scrollTo(0, scrollTop); 
                if (scrollTop < 0 ) {
                    clearInterval(timer);
                    timer=null;
                    div.style.top = "";
                    div.style.display = "none";
                    div.classList.remove("active");
                }
            }, 20);
            
        }
        // console.log(timer);
        document.onscroll = function () {
            var scrollTop = window.scrollY;
            if (scrollTop < 500) {
                div.style.display = "none";
            } else {
                 div.style.display = "block";
            }
            if(timer){
                div.style.display = "block";
            }
        }
    </script>
</body>

</html>